package cn.ultrarisk.scadmin.manager.biz.monitor.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.monitor.dao.ErrorLogDAO;
import cn.ultrarisk.scadmin.manager.biz.monitor.entity.ErrorLog;
import cn.ultrarisk.scadmin.manager.biz.solr.dao.SolrCollectionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 错误日志数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ErrorLogService {
    @Autowired
    private ErrorLogDAO errorLogDAO;
    @Autowired
    private SolrCollectionDAO solrCollectionDAO;

    public void create(List<ErrorLog> logs) {
        Set<String> collectionNames = new HashSet<String>();
        for (ErrorLog log : logs) {
            if (log.getIndexName() != null) {
                collectionNames.add(log.getIndexName());
            }
            /*
            if (log.getParams() != null && log.getParams().length() > 20000) {
                log.setParams(log.getParams().substring(0, 20000));
            }
             */
        }
        Map<String, Integer> collectionIdMap = solrCollectionDAO.getIdMap(collectionNames);
        for (ErrorLog log : logs) {
            if (log.getIndexName() != null) {
                log.setCollectionId(collectionIdMap.get(log.getIndexName()));
            }
        }

        errorLogDAO.createBatch(logs);
    }

    /**
     * 清除过期的errorLog
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(ErrorLog.ERROR_TIME, expiredTime);
        errorLogDAO.delete(query);
    }
}